package com.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class OpenWeatherMapClient implements WeatherApiClient {
    private static final String API_URL = "https://api.openweathermap.org/data/2.5/weather";
    private final String apiKey;
    
    public OpenWeatherMapClient(String apiKey) {
        this.apiKey = apiKey;
    }
    
    @Override
    public String fetchWeatherData(String location) throws IOException {
        String url = String.format("%s?q=%s&appid=%s&units=metric&lang=zh_cn", 
                API_URL, location, apiKey);
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        
        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            throw new IOException("API请求失败，HTTP代码: " + responseCode);
        }
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }
}